<template>
  <div class="xfn-login">
    <el-card class="xfn-login-card">
      <div slot="header">管理员登录</div>
      <div>
        <el-form label-width="100px">
          <el-form-item label="管理员名">
            <el-input placeholder="请输入账号..." v-model="user.uname"></el-input>
          </el-form-item>

          <el-form-item label="管理密码">
            <el-input type="password" placeholder="请输入密码..." v-model="user.pswd"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click.native="doLogin">登录</el-button>
            <el-button @click="doCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<style lang="scss">
.xfn-login {
  .xfn-login-card {
    width: 50%;
    margin: 0 auto;
    .el-card__header {
      text-align: center;
      font-size: 1.2em;
    }
  }
}
</style>

<script>
export default {
  data() {
    return {
      //直接用对象保存表单用户输入的账户和密码 方便后续JSON传输数据给服务器
      user: {
        //开发阶段直接给默认值 正式上线取消
        uname: "admin",
        pswd: "123456",
      },
    };
  },
  methods: {
    doLogin() {
      if (this.user.uname != "" && this.user.pswd != "") {
        //获取后台服务器基础地址 存储在vuex中
        let url = this.$store.state.globalSettings.apiUrl + `/admin/login/${this.user.uname}/${this.user.pswd}`;
        console.log(url);
        //发送请求登录
        this.axios
          .get(url)
          .then((res) => {
            console.log(res.data);
            //如果登录成功
            if (res.data.code == 200) {
              //登录成功
              this.$router.push("/main");
              //并且将用户名储存至vuex中方便接下来的页面进行显示 xxx登录成功
              this.$store.commit("setAdminname", this.user.uname);
            } else {
              //登录失败
              this.$alert("用户名或密码错误", "登录失败", {
                type: "error",
              })
                .then(() => {})
                .catch(() => {
                  //异常穿透
                  console.log("点了x");
                });
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        alert("不能为空");
      }
    },
    doCancel() {
      this.user.uname = "";
      this.user.pswd = "";
    },
  },
};
</script>
